#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>

#define MULTICAST_GROUP "224.1.1.1"
#define PORT 5000
#define BUFFER_SIZE 1024 * 1024

int main()
{
    int sockfd;
    struct sockaddr_in local_addr;
    struct ip_mreq mreq;
    char buffer[BUFFER_SIZE];
    int file_fd;
    ssize_t bytes_received;

    /* 创建 UDP 套接字 */
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    /* 绑定本地地址 */
    memset(&local_addr, 0, sizeof(local_addr));
    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = INADDR_ANY;
    local_addr.sin_port = htons(PORT);

    if (bind(sockfd, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0)
    {
        perror("bind failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    /* 设置多播组 */
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
    mreq.imr_interface.s_addr = INADDR_ANY;
    if (setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
    {
        perror("setsockopt failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    /* 打开文件以写入接收到的数据 */
    if ((file_fd = open("received_file.bin", O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0)
    {
        perror("file open failed");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    /* 接收数据并写入文件 */
    while ((bytes_received = recvfrom(sockfd, buffer, BUFFER_SIZE, 0, NULL, NULL)) > 0)
    {
        if (write(file_fd, buffer, bytes_received) < 0)
        {
            perror("write failed");
            break;
        }
    }

    close(file_fd);
    close(sockfd);
    return 0;
}